package com.fuatnow.game.work;

import com.fuatnow.game.handler.MsgHander;
import com.fuatnow.game.server.WebSocketServer;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * Created by fuatnow on 17/1/18.
 */
public class Worker extends Thread
{
   public static Worker[] _workers;

   public volatile boolean _stop = false;
   private final BlockingQueue<MsgHander> _tasks = new LinkedBlockingDeque<>();

   public static void dispath(MsgHander hander)
   {
       int workdId = getWorkId();
       if(hander == null)
       {
           return;
       }
       _workers[workdId]._tasks.offer(hander);
   }

   public  void run()
   {
       while (!_stop)
       {
           MsgHander hander = null;
           try{
               hander = _tasks.poll(600,TimeUnit.MILLISECONDS);
               if(hander == null)
               {
                   continue;
               }
           }catch (InterruptedException e)
           {

           }

           try
           {
               assert  hander != null;
               hander.processMsg();
           }catch(Exception e)
           {

           }
       }
   }

    public static int getWorkId()
    {
//        return str.hashCode() % WebSocketServer.workNum;
        return new Random().nextInt() % WebSocketServer.workNum;
    }

    public static void  startWorker(int workNum)
    {
        _workers = new Worker[workNum];
        for(int i = 0; i < workNum; i++)
        {
            _workers[i] = new Worker();
            _workers[i].start();
        }
    }

    public static void stopWorkers()
    {
        for(int i = 0; i < WebSocketServer.workNum; i++)
        {
            _workers[i]._stop = true;
        }
    }
}
